/*
 * @Author: your name
 * @Date: 2021-02-22 15:25:56
 * @LastEditTime: 2021-05-28 17:30:11
 * @LastEditors: zws
 * @Description: In User Settings Edit
 * @FilePath: \serve\src\controller\UserController.js
 */
import jsonwebtoken from 'jsonwebtoken';
import { responseTemplate } from '@/utils/responseTemplate';
import regular from '@/utils/regular'
import { dictionaries } from '@/utils/dictionaries'
class UserController {
    async login(ctx) {
        const JWT_SECRET = await dictionaries('get', 'JWT_SECRET')

        const token = jsonwebtoken.sign({ _id: 'a' }, JWT_SECRET[0].value, {
            expiresIn: '1d'
        })
        ctx.body = responseTemplate({ token })
    }
    async registration(ctx) {
        const body = ctx.request.body;
        const token = await dictionaries('get', 'CSRF')
        if (body.token !== token[0].value) {
            ctx.status = 419
            ctx.body = responseTemplate('csrf 请求拦截', 419)
            return;
        }
        if (body.name !== '' && regular.name.test(body.name)) {
            ctx.body = responseTemplate('用户名为数字、字母和中文组成，开头不能为数字2 - 16位', -1)
            return;
        }
        if (body.mail !== '' && regular.mail.test(body.mail)) {
            ctx.body = responseTemplate('请输入正确的电子邮件地址', -1)
            return;
        }

        ctx.body = responseTemplate({ code: 1 })
    }

    async registration_verification(ctx) {
        const body = ctx.request.body;
        // return ctx.body = ctx.body;
        const token = await dictionaries('get', 'CSRF')
        if (body.token !== token[0].value) {
            ctx.status = 419
            ctx.body = responseTemplate('csrf 请求拦截', 419)
            return;
        }
        if (body.name !== '' && regular.name.test(body.name)) {
            ctx.body = responseTemplate('用户名为数字、字母和中文组成,2 - 16位', -1);
            return;
        }

        ctx.body = responseTemplate({ code: 1 })
    }

}

export default new UserController();